const {ipcMain,BrowserWindow} = require("electron")
const getSoure = (url) => {
  return new Promise((resolve,reject)=>{
    const win = new BrowserWindow({
      width:500,
      height:500,
      show:false, // 不显示窗口
      webPreferences:{
        offscreen:true // 只在内存中显示 不显示在屏幕上
      }
    })
    win.loadURL(url)

    win.webContents.on('did-finish-load',async ()=>{
      const title = win.getTitle() // 获取窗口标题标题
      try {
        //nativeImage
      const image = await win.webContents.capturePage()
      if(image.isEmpty()){
        resolve({
          msg:'无法访问该站点，请重新输入'
        })
        return
      }
      const screenshot = image.toDataURL()
      resolve({
        title,
        screenshot,
        url
      })
      } catch (error) {
        console.log(error)
        reject(error)
      }
    })
    
  })
}
ipcMain.handle('on-url-event', async (e,url)=> {
  const result = await getSoure(url)
  return result
})

